<?php

defined('BASEPATH') or die('No direct script access allowed');

class Invite_Controller extends Controller {

    function __call($name, $args) {
        if (is_numeric($name)) {
            $this->user_id($name);
        }
    }

    //初始化方法,不可外部访问,第一个执行,可以省略
    function _init() {
        
    }

    function index() {
        check_level();
        $data['title'] = '邀请好友';
        $data['inviteurl'] = site_url('user/invite/' . $this->auth->user_id . '/', 1);
        $this->view->display("user/invite/index", $data);
    }

    function myinvite() {
        check_level();
        $this->load->helper('ip');
        $state = segment(3, 'all');
        $pagesize = segment(4, 10);
        $page = $this->form->is_submit('post') ? $this->input->post('page', 'intval') : segment(5, 1);
        $page = $page ? $page : 1;
        $offset = ($page - 1) * $pagesize;
        $pageurl = site_url("user/invite/index/{$state}/{$pagesize}/{page}");
        $where = $state == 'all' ? '' : " state = {$state} AND ";
        $result = $this->db->one("SELECT COUNT(*) AS num FROM {pre}invite WHERE {$where} user_id={$this->auth->user_id}");
        $total = $result['num'];
        $data['pagelist'] = $this->page->newget($pageurl, $total, $page, $pagesize);

        $data['list'] = $this->db->simple("SELECT * FROM {pre}invite WHERE {$where} user_id={$this->auth->user_id} order by id desc LIMIT {$offset},$pagesize");
        $data['title'] = '我的邀请记录';
        $data['inviteurl'] = site_url('user/invite/' . $this->auth->user_id . '/', 1);
        $this->view->display("user/invite/myinvite", $data);
    }

    function user_id($id = 0) {
        $id = $id ? intval($id) : intval(segment(3, 0));
        $row = $this->db->one("SELECT id,username FROM {pre}user WHERE id='{$id}'");
        if ($id != 0 && is_array($row)) {
            $invite = $this->cookie->get("invite");
            if ($invite == '') {
                $this->cookie->set("invite", "open");    //通过邀请打开网站
                $this->cookie->set("invite_user_id", $row['id']);
                $this->cookie->set("invite_user_name", $row['username']);
                if ($this->config['scores']['invite_view'] > 0) {
                    scores($this->config['scores']['invite_view'], $row['id'], '邀请链接浏览');
                }
            }
        }
        header("location:/");
    }

}